// API服务封装，整合WebSocket通信
import WebSocketService from './WebSocketService';
import { API_CONFIG, getWebSocketUrl, isUsingMock } from './apiConfig';

// 统一错误处理
const handleApiError = (error, operation) => {
  console.error(`${operation}失败:`, error);
  throw error instanceof Error ? error : new Error(error.message || '操作失败');
};

// 初始化WebSocket服务
export const initApiService = () => {
  const wsUrl = getWebSocketUrl();
  const useMock = isUsingMock();
  
  WebSocketService.init({
    wsUrl,
    enableMock: useMock
  });
  
  console.log('API服务初始化完成', { wsUrl, useMock });
};

// 认证相关API
export const authApi = {
  // 登录
  login: async (email, password) => {
    try {
      console.log('发起登录请求', { email });
      const response = await WebSocketService.sendWithResponse('auth.login', { email, password });
      
      if (response.payload && response.payload.success) {
        // 保存用户信息到localStorage
        localStorage.setItem('user', JSON.stringify(response.payload.data));
        console.log('登录成功');
        return response.payload;
      } else {
        throw new Error(response.payload?.error || '登录失败');
      }
    } catch (error) {
      handleApiError(error, '登录');
    }
  },
  
  // 注册
  register: async (username, email, password) => {
    try {
      console.log('发起注册请求', { username, email });
      const response = await WebSocketService.sendWithResponse('auth.register', { username, email, password });
      
      if (response.payload && response.payload.success) {
        console.log('注册成功');
        return response.payload;
      } else {
        throw new Error(response.payload?.error || '注册失败');
      }
    } catch (error) {
      handleApiError(error, '注册');
    }
  },
  
  // 登出（返回Promise以保持一致性）
  logout: async () => {
    try {
      console.log('发起登出请求');
      // 通过WebSocket通知服务器用户登出
      const response = await WebSocketService.sendWithResponse('auth.logout', {}, 5000);
      
      // 清除本地存储的用户信息
      localStorage.removeItem('user');
      localStorage.removeItem('currentUser');
      console.log('登出成功');
      
      return response.payload || { success: true };
    } catch (error) {
      // 即使WebSocket失败，也要清除本地状态
      localStorage.removeItem('user');
      localStorage.removeItem('currentUser');
      console.log('登出过程中出错，但已清除本地状态:', error);
      return { success: true, warning: '本地登出成功，服务器通信可能失败' };
    }
  },
  
  // 获取用户信息
  getUserProfile: async () => {
    try {
      console.log('获取用户信息');
      const response = await WebSocketService.sendWithResponse('user.profile', {}, 5000);
      
      if (response.payload && response.payload.success) {
        return response.payload.data;
      } else {
        throw new Error(response.payload?.error || '获取用户信息失败');
      }
    } catch (error) {
      handleApiError(error, '获取用户信息');
    }
  }
};

// 聊天相关API
export const chatApi = {
  // 发送消息
  sendMessage: async (message) => {
    try {
      console.log('发送聊天消息');
      const response = await WebSocketService.sendWithResponse('chat.message', { message }, 15000);
      
      if (response.payload && response.payload.success) {
        console.log('消息发送成功并收到回复');
        return response.payload.data;
      } else {
        throw new Error(response.payload?.error || '发送消息失败');
      }
    } catch (error) {
      handleApiError(error, '发送消息');
    }
  },
  
  // 订阅实时消息
  subscribeToMessages: (callback) => {
    // 订阅实时消息推送（如果后端支持）
    console.log('订阅实时消息');
    return WebSocketService.on('chat.message.realtime', callback);
  },
  
  // 订阅消息响应（用于监听所有消息响应）
  subscribeToMessageResponses: (callback) => {
    console.log('订阅消息响应');
    return WebSocketService.on('chat.message.response', callback);
  }
};

// 连接状态管理
export const connectionApi = {
  // 订阅连接状态变化
  subscribeToConnectionStatus: (callback) => {
    console.log('订阅连接状态变化');
    return WebSocketService.on('connection', callback);
  },
  
  // 订阅错误事件
  subscribeToErrors: (callback) => {
    console.log('订阅错误事件');
    return WebSocketService.on('error', callback);
  },
  
  // 手动重连（内部使用mock模式）
  reconnect: () => {
    console.log('执行手动重连');
    WebSocketService.disconnect();
    // 确保重新初始化时仍使用mock模式
    WebSocketService.init({
      wsUrl: getWebSocketUrl(),
      enableMock: true // 强制使用mock模式
    });
  },
  
  // 获取当前连接状态
  getConnectionStatus: () => {
    return {
      isConnected: WebSocketService.isConnected,
      isMockMode: true, // 始终返回使用mock模式
      wsUrl: WebSocketService.wsUrl
    };
  }
};

// 注意：已移除未使用的内部模式切换方法，因为我们现在强制使用mock模式

// 导出默认对象
export default {
  init: initApiService,
  auth: authApi,
  chat: chatApi,
  connection: connectionApi
};